package com.oraclechain.pocketeos.blockchain;

import com.oraclechain.pocketeos.base.Constants;
import com.oraclechain.pocketeos.blockchain.api.EosChainInfo;
import com.oraclechain.pocketeos.blockchain.chain.Action;
import com.oraclechain.pocketeos.blockchain.chain.SignedTransaction;
import com.oraclechain.pocketeos.blockchain.cypto.ec.EosPrivateKey;
import com.oraclechain.pocketeos.blockchain.types.TypeChainId;
import com.oraclechain.pocketeos.blockchain.util.Consts;
import com.oraclechain.pocketeos.coin.BaseCoin;

import java.util.ArrayList;

public class CommonJsSignManager {

    private SignedTransaction txnBeforeSign;
    private static String PERMISSONION = Constants.PERMISSONION;

    private BaseCoin mBaseCoin;
    private String mPrivateKey;
    private String mFromAccountName;
    private String mAction;
    private String mData;

    public CommonJsSignManager(String privateKey, String fromAccountName, String action, String data,
                               BaseCoin baseCoin) {
        mBaseCoin = baseCoin;
        mPrivateKey = privateKey;
        mFromAccountName = fromAccountName;
        mAction = action;
        mData = data;
    }


//    public void sigin2(String privateKey , ScatterSignatureJsBean.ParamsBean.PayloadBean scatterSignatureJsBean) {
//        SignedTransaction txn = new SignedTransaction();
//        txn.setActions(convertAction(scatterSignatureJsBean.getTransaction().getActions()));
//        txn.setExpiration(scatterSignatureJsBean.getTransaction().getExpiration());
//        txn.putKcpuUsage(Long.parseLong(scatterSignatureJsBean.getTransaction().getMax_cpu_usage_ms()));
//        txn.setRef_block_num(Integer.parseInt(scatterSignatureJsBean.getTransaction().getRef_block_num()));
//        txn.setRef_block_prefix(Integer.parseInt(scatterSignatureJsBean.getTransaction().getRef_block_prefix()));
//        EosPrivateKey eosPrivateKey = new EosPrivateKey(privateKey);
//        txn.sign(eosPrivateKey, new TypeChainId(scatterSignatureJsBean.getNetwork().getChainId()));
//    }

    //    private fun convertActionBeanToAction(list: List<ScatterSignatureJsBean.TransactionBean.ActionsBean>): ArrayList<Action> {
//        val actionList = ArrayList<Action>()
//        for (actionbean in list) {
//            val action = Action(actionbean.account, actionbean.name)
//            val typeInferences = ArrayList<TypePermissionLevel>()
//            for (authorizationBean in actionbean.authorization) {
//                Log.e("xxx", "authorizationBean.actor = " + authorizationBean.actor + " , authorizationBean.permission = " + authorizationBean.permission)
//                val typePermissionLevel = TypePermissionLevel(authorizationBean.actor, authorizationBean.permission)
//                typeInferences.add(typePermissionLevel)
//            }
//            action.authorization = typeInferences
//            actionList.add(action)
//        }
//        return actionList
//    }

//    private ArrayList<Action> convertAction(List<ScatterSignatureJsBean.TransactionBean.ActionsBean> list) {
//        ArrayList<Action> actionArrayList = new ArrayList<>();
//        for (ScatterSignatureJsBean.TransactionBean.ActionsBean actionbean :
//                list) {
//            Action action = new Action(actionbean.getAccount(), actionbean.getName());
//            ArrayList<TypePermissionLevel> typeInferences = new ArrayList<TypePermissionLevel>();
//            for (ScatterSignatureJsBean.TransactionBean.ActionsBean.AuthorizationBean authorizationBean :
//                    actionbean.getAuthorization()) {
//                TypePermissionLevel typePermissionLevel = new TypePermissionLevel(authorizationBean.getActor(), authorizationBean.getPermission());
//                typeInferences.add(typePermissionLevel);
//            }
//            action.setAuthorization(typeInferences);
//            actionArrayList.add(action);
//        }
//        return actionArrayList;
//    }
//
//    public void getSign(LifecycleProvider mContext, JsRequestCallBack callBack) {
//        //首先获取chaininfo
//        AccountRetrofitManager.get(mBaseCoin.getWalletType(), ApiService.class)
//                .getEosChainInfo()
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .compose(mContext.bindToLifecycle())
//                .subscribe(new MySubscriber<EosChainInfo>("getEosChainInfo") {
//                    @Override
//                    protected void _onNext(EosChainInfo chainInfoBean) {
//                        sign(chainInfoBean);
//                        callBack.success(txnBeforeSign);
//                    }
//
//                    @Override
//                    protected void _onError(Throwable e, String message) {
//                        callBack.error(e, message);
//                    }
//                });
//
//    }

    private void sign(EosChainInfo chainInfo) {
        String[] permissions = new String[]{mFromAccountName + "@" + PERMISSONION};
        txnBeforeSign = createTransaction(mBaseCoin.getContract(), mAction, mData, permissions, chainInfo);
        EosPrivateKey eosPrivateKey = new EosPrivateKey(mPrivateKey, null);
        txnBeforeSign.sign(eosPrivateKey, new TypeChainId(chainInfo.getChain_id()), null);
    }

    public static SignedTransaction createTransaction(String contract, String actionName, String dataAsHex,
                                                      String[] permissions, EosChainInfo chainInfo) {

        Action action = new Action(contract, actionName);
        action.setAuthorization(permissions);
        action.setData(dataAsHex);

        SignedTransaction txn = new SignedTransaction();
        txn.addAction(action);
        txn.putSignatures(new ArrayList<>());

        if (null != chainInfo) {
            txn.setReferenceBlock(chainInfo.getHeadBlockId());
            txn.setExpiration(chainInfo.getTimeAfterHeadBlockTime(Consts.TX_EXPIRATION_IN_MILSEC));
        }
        return txn;
    }


}
